package com.yunche.yunchebusiness.network

import com.orhanobut.logger.Logger
import com.yunche.yunchebusiness.api.Api
import com.yunche.yunchebusiness.api.ApiService
import com.yunche.yunchebusiness.network.convert.CustomGsonConverterFactory
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 * Create by Crcker on 2018/12/20 11:16
 * Email: Crcker@163.com
 */


object RetrofitManager {

    val service: ApiService by lazy {
        getRetrofit(Api.BASE_URL).create(ApiService::class.java)
    }

    //请求头的拦截器 用于添加公共头
    private val httpLoggingInterceptor: Interceptor
    private val headerInterceptor: Interceptor

    //请求之前的拦截器 修改端口号
    // 初始化拦截器  用于动态更换URL和port  需要在header加类型  不加为默认的base
    init {
        httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        headerInterceptor = Interceptor { chain: Interceptor.Chain ->
            var request = chain.request()
                .newBuilder()
                .build()

            var builder = request
                .url()
                .newBuilder()

            val urlTypes = request.headers(Api.URL_TYPE_KEY)
            val portTypes = request.headers(Api.PORT_TYPE_KEY)

            var newBaseUrl: HttpUrl? = HttpUrl.parse(Api.BASE_URL)
            var newBasePort = Api.BASE_PORT

            if (urlTypes != null && urlTypes.isNotEmpty()) {
                when (urlTypes[0]) {
                    Api.URL_TYPE_BASE -> {
                        newBaseUrl = HttpUrl.parse(Api.BASE_URL)
                    }
                    Api.URL_TYPE_COMMON -> {
                        newBaseUrl = HttpUrl.parse(Api.COMMON_URL)
                    }
                }
            }

            if (portTypes != null && portTypes.isNotEmpty()) {
                when (portTypes[0]) {
                    Api.BASE -> {
                        newBasePort = Api.BASE_PORT
                    }
                    Api.COMMON -> {
                        newBasePort = Api.COMMON_PORT
                    }
                    Api.CHECH_VERSION -> {
                        newBasePort = Api.VERSION_PORT
                    }
                }
            }

            Logger.t("URL:").d(newBaseUrl!!.host() + ":" + newBasePort)

            var newBuilder = builder.host(newBaseUrl!!.host()).port(newBasePort)

            var newRequest = request
                .newBuilder()
                .url(newBuilder.build())
                .header("token", Api.getToken())
                .build()
            chain.proceed(newRequest)
        }
    }


    private fun getRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(getOkhttpClient())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(CustomGsonConverterFactory.create())
            .build()
    }


    private fun getOkhttpClient(): OkHttpClient {
        var httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .addInterceptor(headerInterceptor)
            .proxy(Proxy.NO_PROXY)
            .connectTimeout(30L, TimeUnit.SECONDS)
            .readTimeout(30L, TimeUnit.SECONDS)
            .writeTimeout(30L, TimeUnit.SECONDS)
            .build()
    }

}